<template>
  <el-dialog :model-value="dialogData.isShow" :title="dialogData.id ? '编辑' : '新增'" @close="closeDialog" draggable>
    <el-form :model="form" ref="formRef" :rules="rules" label-width="110px">
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="网站名称" prop="name">
            <el-input v-model="form.name" maxlength="256" placeholder="请输入网站名称"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="采集的网站" prop="url">
            <el-input type="textarea" v-model="form.url" maxlength="2048" placeholder="请输入采集的网站"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="采集脚本名称" prop="scriptName">
            <el-input v-model="form.scriptName" maxlength="255" placeholder="请输入采集脚本名称"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="脚本路径" prop="scriptUrl">
            <el-input v-model="form.scriptUrl" maxlength="255" placeholder="请输入脚本路径"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="采集信息分类" prop="crawlerUrlCategoryId">
            <custom-tree-select v-model:value="form.crawlerUrlCategoryId" :options="crawlerUrlCategoryList" placeholder="请选择上级分类"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="采集频率" prop="frequency">
            <el-input-number v-model="form.frequency" placeholder="采集频率，次/天" style="width: 250px"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="执行时间" prop="executionTime">
            <el-time-picker
                v-model="form.executionTime"
                :disabled-seconds="disabledSeconds"
                value-format="HH:mm:ss"
                placeholder="请选择执行时间"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否需要执行" prop="status">
            <el-select
                v-model="form.status"
                placeholder="请选择是否需要执行"
                style="width: 240px"
            >
              <el-option
                  v-for="item in [{'id': '1', 'title': '是'}, {'id': '0', 'title': '否'}]"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="备注" prop="note">
            <el-input type="textarea" v-model="form.note" maxlength="255" placeholder="请输入备注"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submit">确定</el-button>
        <el-button @click="closeDialog">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {ElMessage, FormInstance, FormRules} from "element-plus";
import {addCrawlerUrl, getCrawlerUrl, updateCrawlerUrl} from "@/api/app/crawlerUrl";
import {getCrawlerUrlCategoryList} from "@/api/app/crawlerUrlCategory";

const formRef = ref<FormInstance>()

const emits = defineEmits<{
  (event: 'refresh'): void
}>()

// 表单
let form: any = ref({
  id: null,
  name: '',
  url: '',
  scriptName: '',
  scriptUrl: '',
  executionTime: null,
  status: '',
  crawlerUrlCategoryId: null,
  frequency: 1,
  note: ''
});


// 效验规则
const rules = reactive<FormRules>({
  name: [
    {
      required: true,
      message: '网站名称必填',
      trigger: 'blur',
    },
  ],
  url: [
    {
      required: true,
      message: '采集的网站必填',
      trigger: 'blur',
    },
  ],
  scriptName: [
    {
      required: true,
      message: '采集的脚本必填',
      trigger: 'blur',
    },
  ],
  scriptUrl: [
    {
      required: true,
      message: '脚本路径必填',
      trigger: 'blur',
    },
  ],
  executionTime: [
    {
      required: true,
      message: '请选择执行时间',
      trigger: 'blur',
    },
  ],
  status: [
    {
      required: true,
      message: '请选择可执行状态',
      trigger: 'blur',
    },
  ],
  crawlerUrlCategoryId: [
    {
      required: true,
      message: '采集信息源分类必填',
      trigger: 'blur',
    },
  ],
})

// 获取详情
const getDetails = (id: string) => {
  getCrawlerUrl(id).then(res => {
    form.value = Object.assign({}, form.value, res);
  })
}

// 弹框数据
const dialogData = reactive({
  isShow: false,
  id: null
})

// 打开弹框
const openDialog = async (id: string) => {
  dialogData.isShow = true;
  dialogData.title = '新增采集记录';
  if (id) {
    dialogData.id = id;
    dialogData.title = '编辑采集记录';
    getDetails(id);
  }
  getAllCrawlerUrlCategory()
}

// 关闭弹框
const closeDialog = () => {
  dialogData.isShow = false;
  dialogData.id = null;
  form.value = {};
}

// 提交
const submit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate((valid: any) => {
    if (valid) {
      let data = form.value;
      if (data.id) {
        updateCrawlerUrl({...data}).then(() => {
          ElMessage.success('操作成功');
          closeDialog();
          emits('refresh');
        })
      } else {
        addCrawlerUrl({...data}).then(() => {
          ElMessage.success('操作成功');
          closeDialog();
          emits('refresh');
        })
      }
    }
  })
}

const crawlerUrlCategoryList = ref([])

const getAllCrawlerUrlCategory = () => {
  getCrawlerUrlCategoryList({}).then((res: any) => {
    if (res.length) {
      let data = [...res]
      function fun(dataList: any) {
        dataList.map((item: any) => {
          if (item.children) fun.call(this, item.children)
          Object.assign(item, {name: item.categoryName})
        })
      }
      fun.call(this, data)
      crawlerUrlCategoryList.value = data
    }
  })
}

const makeRange = (start: number, end: number) => {
  const result: number[] = []
  for (let i = start; i <= end; i++) {
    result.push(i)
  }
  return result
}

const disabledSeconds = () => {
  return makeRange(1, 59)
}
defineExpose({
  openDialog,
});
</script>

<style scoped></style>
